# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

import pymongo


class TaobaoPipeline(object):
    def process_item(self, item, spider):
        return item


class MongoPipeline(object):
    """保存到MongoDB，详情见 https://docs.scrapy.org/en/latest/topics/item-pipeline.html#write-items-to-mongodb"""
    collection_name = 'products'  # 集合名（"表"）

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        """信息注入，包括设置MongoDB地址与库名"""
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
        )

    def open_spider(self, spider):
        """打开MongoDB数据库"""
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def process_item(self, item, spider):
        """插入数据"""
        # 保存报错must not contain '.',将key的核对关闭，默认打开
        self.db[self.collection_name].insert(dict(item), check_keys=False)
        return item

    def close_spider(self, spider):
        """关闭MongoDB数据库"""
        self.client.close()
